package com.jrx.anytxn.common.uitl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jrx.anytxn.common.exception.TxnBeanMappingException;
import net.sf.cglib.beans.BeanCopier;
import net.sf.cglib.beans.BeanMap;


import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * 基于cglib的bean属性拷贝，只支持同名同类型的字段拷贝
 */
public class BeanMapping {
    private static final Map<String, BeanCopier> beanCopierCache = new ConcurrentHashMap<>();

    private static final Map<String,Map<String, Method>> objMethodMapCache = new ConcurrentHashMap<>();

    private static String generateKey(Class<?> class1, Class<?> class2) {
        return class1.getName() + class2.getName();
    }

    private static BeanCopier getBeanCopier(Class sourceClass, Class targetClass) {
        String beanKey = generateKey(sourceClass, targetClass);
        BeanCopier copier;
        try {
            if (!beanCopierCache.containsKey(beanKey)) {
                copier = BeanCopier.create(sourceClass, targetClass, false);
                beanCopierCache.put(beanKey, copier);
            } else {
                copier = beanCopierCache.get(beanKey);
            }
        } catch (Exception ex) {
            throw new TxnBeanMappingException(ex);
        }

        return copier;
    }

    private static <S, D> D copyOne(BeanCopier copier, S source, Class<D> targetClass, Converter<S, D> biConsumer) {
        try {
            D distObj = targetClass.newInstance();
            copier.copy(source, distObj, null);

            // 特殊需要处理的字段
            if(distObj != null && biConsumer != null) {
                biConsumer.convert(source, distObj);
            }
            return distObj;
        } catch (Exception e) {
            throw new TxnBeanMappingException(e);
        }
    }

    /**
     * 将原对象的属性拷贝到目标对象中,不生成新的对象
     * @param source 原对象
     * @param target 目标对象
     * @param <S> 原数据类型
     * @param <D> 目标数据类型
     */
    public static <S, D> void copy(S source, D target) {
        BeanCopier copier = getBeanCopier(source.getClass(), target.getClass());
        try {
            copier.copy(source, target, null);
        } catch (Exception ex) {
            throw new TxnBeanMappingException(ex);
        }
    }

    /**
     * 将原对象的属性拷贝到目标对象中
     * @param source 原对象
     * @param targetClass 目标类型
     * @param <S> 原数据类型
     * @param <D> 目标数据类型
     * @return 返回目标对象
     */
    public static <S, D> D copy(S source, Class<D> targetClass) {
        return copy(source, targetClass, null);
    }

    /**
     * 将原对象的属性拷贝到目标对象中，允许对特定字段单独处理
     * @param source 原对象
     * @param targetClass 目标类型
     * @param converter 自定义转换器
     * @param <S> 原数据类型
     * @param <D> 目标数据类型
     * @return 返回目标对象
     */
    public static <S, D> D copy(S source, Class<D> targetClass, Converter<S, D> converter) {
        BeanCopier copier = getBeanCopier(source.getClass(), targetClass);
        return copyOne(copier, source, targetClass, converter);
    }

    /**
     * 批量将原对象的属性拷贝到目标对象中
     * @param sourceList 原对象集合
     * @param targetClass 目标类型
     * @param <S> 原数据类型
     * @param <D> 目标数据类型
     * @return 返回目标对象集合
     */
    public static <S, D> List<D> copyList(List<S> sourceList, Class<D> targetClass) {
        return copyList(sourceList, targetClass, null);
    }

    /**
     * 批量将原对象的属性拷贝到目标对象中，允许对特定字段单独处理
     * @param sourceList 原对象集合
     * @param targetClass 目标类型
     * @param converter 自定义转换器
     * @param <S> 原数据类型
     * @param <D> 目标数据类型
     * @return 返回目标对象集合
     */
    public static <S, D> List<D> copyList(List<S> sourceList, Class<D> targetClass, Converter<S, D> converter) {
        if (sourceList == null || sourceList.isEmpty()) {
            return new ArrayList<>();
        }

        List<D> resultList = new ArrayList<>(sourceList.size());
        Class sourceClass = sourceList.get(0).getClass();

        BeanCopier copier = getBeanCopier(sourceClass, targetClass);
        for (S source : sourceList) {
            resultList.add(copyOne(copier, source, targetClass, converter));
        }

        return resultList;
    }

    /**
     * 将对象装换为map
     * @param bean
     * @return
     */
    public static <T> Map<String, Object> beanToMap(T bean) {
        Map<String, Object> map = Maps.newHashMap();
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                map.put(key+"", beanMap.get(key));
            }
        }
        return map;
    }

    /**
     * 将map装换为javabean对象
     * @param map
     * @param bean
     * @return
     */
    public static <T> T mapToBean(Map<String, Object> map,T bean) {
        BeanMap beanMap = BeanMap.create(bean);
        beanMap.putAll(map);
        return bean;
    }

    /**
     * 将List<T>转换为List<Map<String, Object>>
     * @param objList
     * @return
     */
    public static <T> List<Map<String, Object>> objectsToMaps(List<T> objList) {
        List<Map<String, Object>> list = Lists.newArrayList();
        if (objList != null && objList.size() > 0) {
            Map<String, Object> map;
            T bean;
            for (T t : objList) {
                bean = t;
                map = beanToMap(bean);
                list.add(map);
            }
        }
        return list;
    }

    /**
     * 将List<Map<String,Object>>转换为List<T>
     * @param maps
     * @param clazz
     * @return
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public static <T> List<T> mapsToObjects(List<Map<String, Object>> maps,Class<T> clazz)  {
        List<T> list = Lists.newArrayList();
        if (maps != null && maps.size() > 0) {
            Map<String, Object> map;
            T bean;
            for (Map<String, Object> stringObjectMap : maps) {
                map = stringObjectMap;
                try {
                    bean = clazz.newInstance();
                } catch (InstantiationException | IllegalAccessException e) {
                    throw new TxnBeanMappingException(e);
                }
                mapToBean(map, bean);
                list.add(bean);
            }
        }
        return list;
    }

    public interface Converter<S, D> {
        void convert(S source, D dist);
    }

    /**
     * 将后一个对象不为空的属性复制到前一个对象
     * @param source
     * @param copy
     * @param <S>
     */
    public static <S> void copyUpdate(S source,S copy) {
        Field[] fields = source.getClass().getDeclaredFields();
        Arrays.stream(fields).forEach(field -> {
            try {
                String getMethodName = "get" + StringUtils.upperCase(field.getName());
                Method getMethod;
                Map<String, Method> methodMapCache = objMethodMapCache.get(source.getClass().getName());
                if (null != methodMapCache && methodMapCache.containsKey(getMethodName)) {
                    getMethod = methodMapCache.get(getMethodName);
                }else{
                    getMethod = source.getClass().getMethod(getMethodName);
                    if(null == methodMapCache) {
                        methodMapCache = new ConcurrentHashMap<>();
                    }
                    methodMapCache.put(getMethodName, getMethod);
                    getMethod.setAccessible(true);
                    objMethodMapCache.put(source.getClass().getName(),methodMapCache);

                }
                Object obj = getMethod.invoke(copy);
                if (null == obj) {
                    return;
                }

                Method setMethod;
                String setMethodName = "set" + StringUtils.upperCase(field.getName());
                if (methodMapCache.containsKey(setMethodName)) {
                    setMethod = methodMapCache.get(setMethodName);
                }else{
                    setMethod = source.getClass().getMethod(setMethodName,obj.getClass());
                    methodMapCache.put(setMethodName, setMethod);
                    setMethod.setAccessible(true);
                    objMethodMapCache.put(source.getClass().getName(),methodMapCache);
                }
                setMethod.invoke(source, obj);
            }catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    }

}
